package com.itheima.web;

import com.itheima.model.ResponseResult;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.util.*;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * @作者 itcast
 * @创建日期 2021/3/8 14:45
 **/
@WebServlet(loadOnStartup = 1,value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 读取请求体参数， 得到json串
        String paramJson = RequestUtils.ReadAsChars(req);
        System.out.println("前端请求参数: "+paramJson);
        // 将json串转为map
        Map<String,String> info = JsonUtils.jsonToObj(Map.class, paramJson);
        String name = info.get("name");
        String pass = info.get("pass");
        // 登录
        UserService userService = new UserServiceImpl();
        String encode = MD5Utils.encode(pass);
        User user = userService.login(name,encode);
        Map map = new HashMap();
        if(user!=null){
            Long userId = user.getId();
            // 生成token
            String token = AppJwtUtil.getToken(userId);
            map.put("token",token);
            ResponseUtils.okResult(resp,map);
        }else{
            ResponseUtils.errorResult(resp,"用户名或者密码错误！");
        }
    }
}
